#!/usr/bin/env python
# coding: utf-8

# In[1]:


import json
import os
import dashscope
from dashscope.api_entities.dashscope_response import Role
#dashscope.api_key = "sk-563b2828bef9409c88d8ecc4cab85536"

#from openai import OpenAI

#pip install python-dotenv
from dotenv import load_dotenv

# 加载 .env 文件中的环境变量
load_dotenv()

dashscope.api_key = os.getenv("DASHSCOPE_API_KEY")

# 编写你的函数
def get_current_weather(location, unit="摄氏度"):
    # 获取指定地点的天气
    temperature = -1

    #判断位置中是否含有大连或者Dalian字符串
    if '大连' in location or 'Dalian' in location:
        temperature = 10
    if location=='上海':
        temperature = 36
    if location=='深圳':
        temperature = 37
    weather_info = {
        "location": location,
        "temperature": temperature,
        "unit": unit,
        "forecast": ["晴天", "微风"],
    }

    #json.dumps()讲json对象转换为json字符串
    return json.dumps(weather_info)

# 封装模型响应函数
def get_response(messages):
    try:
        response = dashscope.Generation.call(
            model='qwen-turbo',
            messages=messages,
            functions=functions,
            result_format='message'
        )
        return response
    except Exception as e:
        print(f"API调用出错: {str(e)}")
        return None

# 使用function call进行QA
def run_conversation():
    query = "大连的天气怎么样？"
    messages=[{"role": "user", "content": query}]
    
    # 得到大模型的第一次响应
    response = get_response(messages)
    if not response or not response.output:
        print("获取响应失败")
        return None
        
    #print('response=', response)
    #{"status_code": 200, "request_id": "b787b97b-2cb3-9765-a466-3de66cf38de3", "code": "", "message": "", "output": {"text": null, "finish_reason": null, "choices": [{"finish_reason": "function_call", "message": {"role": "assistant", "content": "", "function_call": {"name": "get_current_weather", "arguments": "{\"location\": \"Dalian, Liaoning\"}"}}}]}, "usage": {"input_tokens": 206, "output_tokens": 22, "prompt_tokens_details": {"cached_tokens": 0}, "total_tokens": 228}}
    
    message = response.output.choices[0].message
    messages.append(message)
    
    #获取大模型第一次返回的信息
    #print('message=========', message)
    #{
    #     "role": "assistant",
    #     "content": "",
    #     "function_call": {
    #         "name": "get_current_weather",
    #         "arguments": "{\"location\": \"Dalian, Liaoning\"}"
    #     }
    # }

    #print('messages=========', messages)
    #[{
    #     'role': 'user',
    #     'content': '大连的天气怎样'
    # }, Message({
    #     'role': 'assistant',
    #     'content': '',
    #     'function_call': {
    #         'name': 'get_current_weather',
    #         'arguments': '{"location": "Dalian, Liaoning"}'
    #     }
    # })]

    #return ;
    
    # Step 2, 判断用户是否要call function
    
    #判断用户在message中定义了function_call的属性
    if hasattr(message, 'function_call') and message.function_call:
        
        #获取function call对象
        function_call = message.function_call
        # {
        #     "name": "get_current_weather",
        #     "arguments": "{\"location\": \"Dalian, Liaoning\"}"
        # }


        #获取工具名称（函数名称）
        tool_name = function_call['name']
        

        #获取传递给工具的参数（实际函数参数）
        arguments = json.loads(function_call['arguments'])
        #print('arguments=', arguments)
        #{'location': 'Dalian, Liaoning'}


        # Step 3, 执行function call
        # tool_response = get_current_weather(
        #     location=arguments.get('location'),
        #     unit=arguments.get('unit'),
        # )
        tool_response = globals()[tool_name](**arguments)

        

        #print('tool_response===',tool_response)
        # {
        #     "location": "Dalian, Liaoning",
        #     "temperature": 10,
        #     "unit": null,
        #     "forecast": ["晴天", "微风"]
        # }

        #获取工具返回的结果
        tool_info = {"role": "function", "name": tool_name, "content": tool_response}
        # print('tool_info=', tool_info)
        # {
        #     'role': 'function',
        #     'name': 'get_current_weather',
        #     'content': '{"location": "Dalian, Liaoning", "temperature": 10, "unit": "\\u6444\\u6c0f\\u5ea6", "forecast": ["\\u6674\\u5929", "\\u5fae\\u98ce"]}'
        # }

        #拼接工具返回的消息
        messages.append(tool_info)
        #print('messages=', messages)
        # [{
        #     'role': 'user',
        #     'content': '大连的天气怎样'
        # }, Message({
        #     'role': 'assistant',
        #     'content': '',
        #     'function_call': {
        #         'name': 'get_current_weather',
        #         'arguments': '{"location": "Dalian, Liaoning"}'
        #     }
        # }), {
        #     'role': 'function',
        #     'name': 'get_current_weather',
        #     'content': '{"location": "Dalian, Liaoning", "temperature": 10, "unit": null, "forecast": ["\\u6674\\u5929", "\\u5fae\\u98ce"]}'
        # }]
        
        
        #Step 4, 得到第二次响应
        response = get_response(messages)
        if not response or not response.output:
            print("获取第二次响应失败")
            return None
            
        # print('response=', response)
        # {
        #     "status_code": 200,
        #     "request_id": "cdf25eab-9755-9384-b843-bc263034616d",
        #     "code": "",
        #     "message": "",
        #     "output": {
        #         "text": null,
        #         "finish_reason": null,
        #         "choices": [{
        #             "finish_reason": "stop",
        #             "message": {
        #                 "role": "assistant",
        #                 "content": "大连当前的温度是10摄氏度，天气状况为晴朗，伴有微风。"
        #             }
        #         }]
        #     },
        #     "usage": {
        #         "input_tokens": 298,
        #         "output_tokens": 24,
        #         "total_tokens": 322
        #     }
        # }


        message = response.output.choices[0].message
        return message
    
    
    return message


#注册函数，让大模型自动调用
functions = [
    {
      'name': 'get_current_weather',
      #这里解释给大模型听的
      'description': 'Get the current weather in a given location.',
      'parameters': {
            'type': 'object',
            'properties': {
                'location': {
                    'type': 'string',
                    'description': 'The city and state, e.g. San Francisco, CA'
                },
                'unit': {'type': 'string', 'enum': ['celsius', 'fahrenheit']}
            },
        'required': ['location']
      }
    }
]

if __name__ == "__main__":
    result = run_conversation()
    if result:
        print("最终结果:", result)
    else:
        print("对话执行失败")